<?php
/**
 * Created by PhpStorm.
 * Author: QinShuai
 * Email: qinshuai0423@qq.com
 * Date: 2021/8/10
 */

namespace common\models;

use yii\base\Model;
use yii\web\UploadedFile;


class Upload extends Model
{
    /**
     * @var UploadedFile[]
     */
    public $imageFile;
    /**
     * 上传路径
     * @var string
     */
    public $path = './uploads/';
    /**
     * 上传后返回路径
     * @var
     */
    public $basename;

    public function rules()
    {
        return [
            [['imageFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
        ];
    }

    /**
     * @param $path
     */
    public function setPath($path)
    {
        $this->path = $path;
    }

    public function upload()
    {
        if ($this->validate()) {
            $dir = $this->path . date('Ymd');

            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            $this->basename = $dir . '/' . $this->imageFile->baseName . '.' . $this->imageFile->extension;
            $this->imageFile->saveAs($this->basename);
            return true;
        } else {
            return false;
        }
    }
}